<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>分 k 组后排序</title>
</head>

<body>
  <script>
    const reverseKGroup = (head, k) => {
      // 终止条件，看后面的是否小于k
      let [end, start] = [head, head]
      // 判断长度是否大于k,end负责记录下次需要继续的位置
      for (let i = 0; i < k; i++) {
        end = end.next
        if (!end) return head
      }
      // 因为反转链表所以start变成了新链表的尾结点，end为老链表需要继续遍历的节点
      let newHead = reserve(start, end)
      start.next = reverseKGroup(end, k)
      return newHead
      // 反转链表
    };
    const reserve = (start, end) => {
      let [pre, current] = [null, start]
      while (current !== end) [current.next, pre, current] = [pre, current, current.next]
      return pre
    }
    console.log(reverseKGroup([1, 2, 3, 4, 5], 2))
  </script>
</body>

</html>